package com.dgw.exception;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dgw.enums.ResultEnum;
import com.dgw.utils.Result;
import com.dgw.utils.ResultUtil;

/**
 * 全局异常处理器
 * @author dgw
 *
 */
@ControllerAdvice
public class MyExceptionHandler {
	
	private final static Logger logger=LoggerFactory.getLogger(MyExceptionHandler.class);
	
	@SuppressWarnings("rawtypes")
	@ExceptionHandler(value=Exception.class)
	@ResponseBody
	public Result handle(Exception e){
		 
		if(e instanceof MyException){
			MyException exception=(MyException)e;
			return ResultUtil.error(exception.getCode(), e.getMessage());
		}else if(e instanceof BindException){
			BindException exception=(BindException)e;
			List<ObjectError> allErrors = exception.getAllErrors();
			String defaultMessage="";
			for(ObjectError objectError:allErrors){
				defaultMessage+= objectError.getDefaultMessage()+";";
			}
			return ResultUtil.error(ResultEnum.PARAM_VALID_FAIL.getCode(),defaultMessage);
		}else{ 
			logger.error("【系统异常】 {}",e);
			return ResultUtil.error(ResultEnum.UNKOWN);
		}
		
	}

}
